package com.books.controller.personal_center;

import com.books.dao.NewQuestionDao;
import com.books.model.bo.Result;
import com.books.model.entity.address.Receiving_address;
import com.books.model.entity.backcontroller.*;
import com.books.model.entity.book.Books;
import com.books.model.entity.book.Ebook;
import com.books.model.entity.comment.Comment;
import com.books.model.entity.common.CommentView;
import com.books.model.entity.common.People;
import com.books.model.entity.login_regis.UserLogin;
import com.books.model.entity.order.BuyOrder;
import com.books.model.entity.order.OrderList;
import com.books.model.entity.question.NewQuestion;
import com.books.service.address.IAddressService;
import com.books.service.admin.IAdminService;
import com.books.service.book.impl.BookServiceImpl;
import com.books.service.book.impl.EbookServiceImpl;
import com.books.service.comment.ICommentService;
import com.books.service.connection.IConnectionService;
import com.books.service.login_regis.impl.UserLoginServiceImpl;
import com.books.service.order.IBuyOrderServer;
import com.books.service.order.IOrderListServer;
import com.books.service.people.IPeopleService;
import com.books.util.Md5Util;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * @Author 饿熊的咆哮
 * @Date 2021/9/24 19:54
 * @Version 1.0
 */
@Controller
@RequestMapping("/personal")
public class PersonalCenterController {
    @Autowired
    private BookServiceImpl bookService;

    @Autowired
    private EbookServiceImpl ebookService;
    @Autowired
    private IConnectionService connectionService;
    @Autowired(required = false)
    private Receiving_address receiving_address;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private UserLoginServiceImpl userLoginService;
    @Autowired
    private IAdminService iAdminService;
    @Autowired
    private IPeopleService peopleService;
    @Autowired
    private People peoples;
    @Autowired
    private UserLogin userLogin;
    @Autowired
    private IBuyOrderServer buyOrderServer;
    @Autowired
    private IOrderListServer orderListServer;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private NewQuestionDao newQuestionDao;

    @GetMapping("/center")
    public String login(Model model,HttpServletRequest request){
        HttpSession session=request.getSession();
        People people = (People) session.getAttribute("people");
        Integer peopleId = people.getPeopleId();
        List<Chat> chats = adminService.findRead(peopleId,false);
        JSONArray chatJson = JSONArray.fromObject(chats);
        model.addAttribute("chatJson",chatJson);

        UserLogin user = (UserLogin) session.getAttribute("user");
        if (user!=null){
            Integer peopleId1 = peopleService.findPeopleId(user.getAccount());
            List<NewQuestion> newQuestions = newQuestionDao.findNewQuestionByPeopleId(peopleId1);
            JSONArray newQuestionJson = JSONArray.fromObject(newQuestions);
            request.setAttribute("newQuestions",newQuestionJson);
        }
        return "personal_center/center";
    }

    @GetMapping("/getChat")
    @ResponseBody
    public JSONArray getChat(Integer peopleId){
        List<Chat> chats = adminService.findRead(peopleId,false);
        JSONArray chatJson = JSONArray.fromObject(chats);
        return chatJson;
    }


    @GetMapping("/sendReply")
    @ResponseBody
    public Result sendReply(Integer chatId,Integer takePeopleId,Integer sendPeopleId,String chat,String sendTime){
        Chat sendChat = new Chat();
        sendChat.setSendPeopleId(sendPeopleId);
        sendChat.setTakePeopleId(takePeopleId);
        sendChat.setChat(chat);
        sendChat.setSendTime(sendTime);
        adminService.addChat(sendChat);
        adminService.updateChat(true,chatId);
        return new Result("200","发送成功");
    }

    @GetMapping("/imgUrl")
    @ResponseBody
    public String imgUrl(HttpServletRequest request,String phone){
        HttpSession session=request.getSession ();
//        userLogin= (UserLogin) session.getAttribute ("user");
//        String phone =userLogin.getAccount ();
        String headUrl=peopleService.findHeadUrl (phone);
        return headUrl;
    }



    @PostMapping("/center")
    @ResponseBody
    public Result update(HttpServletRequest request, People people){
        HttpSession session=request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
//        System.out.println (userLogin);
        String phone=userLogin.getAccount ();
        peoples=peopleService.getPeopleByAccount (phone);
        System.out.println (people);
        System.out.println (peoples);
        peoples.setName (people.getName());
        peoples.setBirthday (people.getBirthday ());
        peoples.setSex (people.getSex ());
        peoples.setAddress (people.getAddress ());
        peoples.setHeadUrl (people.getHeadUrl ());


        int n = peopleService.modifyPerson (peoples,phone);

        peopleService.modifyUname (people.getName (),phone);
        if(n!=0) {
            return new Result ("200", "更新成功");
        }
        return new Result ("500","更新失败");

    }

    @PostMapping("/add")
    @ResponseBody
    public Result add(HttpServletRequest request, Receiving_address address){
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        Integer people_id = peopleService.findPeopleId (phone);
        receiving_address.setName (address.getName ());
        receiving_address.setPhone (address.getPhone ());
        receiving_address.setAddress (address.getAddress ());
        receiving_address.setZipCode (address.getZipCode ());
        receiving_address.setPeopleId (people_id);
        System.out.println (address);
        System.out.println (receiving_address);
        int n = addressService.findAddress (people_id);
//        int n = addressService.addAddress (receiving_address);
        System.out.println ("n"+n);
        if(n<5){
//            int len = n+1+people_id*10;
//            receiving_address.setId (len);
            addressService.addAddress (receiving_address);
            return new Result ("200","添加成功");
        }else if(n==5){
            return new Result ("300","最多添加5条收货地址");
        }
        return new Result ("500","添加失败");
    }

    @GetMapping("/address")
    @ResponseBody
    public Result find(HttpServletRequest request,String account) {
        HttpSession session = request.getSession ();
        peoples = peopleService.getPeopleByAccount (account);
        List<Receiving_address> addressList = addressService.findAllByPid (peoples.getPeopleId ());
        session.setAttribute ("address", addressList);
//        System.out.println (addressList);
        JSONArray jsonArray = JSONArray.fromObject (addressList);
        return new Result ("200", "地址展示",jsonArray);
    }

    @GetMapping("/del")
    @ResponseBody
    public Result del(HttpServletRequest request,Integer id){
//        System.out.println ("address_id"+id);
        addressService.delById (id);
        return new Result ("200","删除成功");
    }

    @PostMapping("/changePsw")
    @ResponseBody
    public Result changePsw(HttpServletRequest request,String email,String ops,String psw){
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        String password = userLoginService.loginByAccount (phone).getPassword ();
        if(!password.equals (Md5Util.code(ops))){
            return new Result ("500","旧密码有误");
        }else{
            peoples = peopleService.getPeopleByAccount (phone);
            peoples.setEmail (email);
            peopleService.change (peoples,peoples.getPeopleId ());
            userLoginService.updateUserLogin (psw,email,phone);
            return new Result ("200","修改成功");
        }
    }

    @GetMapping("/connection")
    @ResponseBody
    public JSONArray connection(HttpServletRequest request,Integer uid){
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        Integer peopleId = peopleService.findPeopleId (phone);
        List<Connection> connectionList = connectionService.connection (peopleId);
//        System.out.println (peopleId);
//        System.out.println (connectionList);
        List<ConnectionBook> connectionBooks = new ArrayList<> ();
        for (Connection connection : connectionList) {
            if(connection.getBookType ()==1){
                ConnectionBook connectionBook = new ConnectionBook ();
                Books books =bookService.getById (connection.getBookId ());
                connectionBook.setId (connection.getId ());
                connectionBook.setBookId (books.getBkId ());
                connectionBook.setBookType (books.getCategoryId ());
                connectionBook.setPictureUrl (books.getPictureUrl ());
                connectionBook.setTitle (books.getTitle ());
                connectionBook.setPrice (books.getPrice ());
                connectionBooks.add (connectionBook);
//                System.out.println (connectionBooks);
            }else if(connection.getBookType ()==2){
                ConnectionBook connectionBook = new ConnectionBook ();
                Ebook ebook =ebookService.getById (connection.getBookId ());
                connectionBook.setId (connection.getId ());
                connectionBook.setBookId (ebook.getEbkId ());
                connectionBook.setBookType (ebook.getCategoryId ());
                connectionBook.setPictureUrl (ebook.getPictureUrl ());
                connectionBook.setTitle (ebook.getTitle ());
                connectionBook.setPrice (ebook.getPrice ());
                connectionBooks.add (connectionBook);
//                System.out.println ("-------");
//                System.out.println (connectionBooks);
            }
        }
        JSONArray jsonArray = JSONArray.fromObject (connectionBooks);
        // System.out.println (jsonArray);
        //System.out.println (connectionBooks);
        return jsonArray;
    }


    @GetMapping("/delconnection")
    @ResponseBody
    public Result delconnection (HttpServletRequest request,Integer id){
        connectionService.del (id);

        return new Result ("200","删除成功");
    }

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file,HttpServletRequest request){
        HttpSession session=request.getSession();
        UserLogin userLogin= (UserLogin) session.getAttribute("user");
        People people=peopleService.getPeopleByAccount(userLogin.getAccount());
        System.out.println(people);
        //获取属性
        String filename = file.getOriginalFilename();
        //重新生成一个新的名称
        String newFileName = UUID.randomUUID().toString()+"_"+filename;
        people.setHeadUrl(newFileName);
        peopleService.change(people,people.getPeopleId());
        //获取imgs的绝对路径
        ///Users/admin/Documents/success/teaching/wksp/spring-j13/springboot-j03s/src/main/webapp/
        String path = request.getServletContext().getRealPath("/");

        //写出去
        File f = new File(path+"imgs/"+newFileName);
        try {
            file.transferTo(f);
        } catch (IOException e) {

            e.printStackTrace();
            return new Result("500","文件上传失败");
        }
        session.setAttribute("people",people);
        return new Result("200","文件上传成功",newFileName);
    }

    @GetMapping("/age")
    @ResponseBody
    public Integer getAge(HttpServletRequest request,Integer uid) throws ParseException {
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        Date date = peopleService.getBirthday (phone);


        int age = 0;
        Calendar born = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        if (date != null) {
            now.setTime(new Date());
            born.setTime(date);
            if (born.after(now)) {
                throw new IllegalArgumentException("年龄不能超过当前日期");
            }
            age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
            int nowDayOfYear = now.get(Calendar.DAY_OF_YEAR);
            int bornDayOfYear = born.get(Calendar.DAY_OF_YEAR);
//            System.out.println("nowDayOfYear:" + nowDayOfYear + " bornDayOfYear:" + bornDayOfYear);
            if (nowDayOfYear < bornDayOfYear) {
                age -= 1;
            }
        }
//        JSONArray jsonArray = JSONArray.fromObject (age);
//        return jsonArray;
//        System.out.println ("age======"+age);
        return age;
    }

    @GetMapping("/vip")
    @ResponseBody
    public String getVip(HttpServletRequest request){
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        People people = peopleService.findByPhone (phone);
        Integer vipId = people.getVipId ();
//        System.out.println ("vip==============="+vipId);
        Vip vip = iAdminService.findByVipId (vipId);
        String vipName = vip.getVipName ();
        return vipName;

    }

//    个人中心主页 待发货显示
    @GetMapping("/b")
    @ResponseBody
    public Integer getB(HttpServletRequest request) {
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        People people = peopleService.findByPhone (phone);
        int count =0 ;
        Integer peopleId = peopleService.findPeopleId (phone);
        List<BuyOrder> buyOrderList = buyOrderServer.findAllOrder (peopleId);
        for (BuyOrder buyOrder : buyOrderList) {
            String buyId = buyOrder.getBuyId ();
            List<OrderList> orderLists = orderListServer.findAllList (buyId);
            if(orderLists!=null && orderLists.size ()>0){
                for (OrderList orderList : orderLists) {
                    if(orderList.getBuyStatus ()==1){
                        count++;
                    }
                }
            }
        }

        return count;
    }

    @GetMapping("/c")
    @ResponseBody
    public Integer getC(HttpServletRequest request) {
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        People people = peopleService.findByPhone (phone);
        int count =0 ;
        Integer peopleId = peopleService.findPeopleId (phone);
        List<BuyOrder> buyOrderList = buyOrderServer.findAllOrder (peopleId);
        for (BuyOrder buyOrder : buyOrderList) {
            String buyId = buyOrder.getBuyId ();
            List<OrderList> orderLists = orderListServer.findAllList (buyId);
            if(orderLists!=null && orderLists.size ()>0){
                for (OrderList orderList : orderLists) {
                    if(orderList.getBuyStatus ()==2){
                        count++;
                    }
                }
            }
        }

        return count;
    }


    @GetMapping("/d")
    @ResponseBody
    public Integer getD(HttpServletRequest request) {
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        People people = peopleService.findByPhone (phone);
        int count =0 ;
        Integer peopleId = peopleService.findPeopleId (phone);
        List<BuyOrder> buyOrderList = buyOrderServer.findAllOrder (peopleId);
        for (BuyOrder buyOrder : buyOrderList) {
            String buyId = buyOrder.getBuyId ();
            List<OrderList> orderLists = orderListServer.findAllList (buyId);
            if(orderLists!=null && orderLists.size ()>0){
                for (OrderList orderList : orderLists) {
                    if(orderList.getBuyStatus ()==3){
                        count++;
                    }
                }
            }
        }

        return count;
    }



    @GetMapping("/comment")
    @ResponseBody
    public JSONArray comment(HttpServletRequest request){
        HttpSession session = request.getSession ();
        userLogin= (UserLogin) session.getAttribute ("user");
        String phone = userLogin.getAccount ();
        Integer peopleId = peopleService.findPeopleId (phone);
        List<Comment> comments = commentService.findCommentByPeopleId (peopleId);
        List<CommentView> commentViews = new ArrayList<> ();
        for (Comment comment : comments) {
            CommentView commentView = new CommentView ();
            if(comment.getBookTypeId ()==1){
                Books books = bookService.getById (comment.getBookId ());
                commentView.setBookImg (books.getPictureUrl ());
                commentView.setTitle (books.getTitle ());
                commentView.setCommentTime (comment.getCommentTime ());
                commentView.setCommentStar (comment.getCommentStar ());
                commentView.setComment (comment.getComment ());
                commentViews.add (commentView);
            }else{
                Ebook ebook = ebookService.getById (comment.getBookId ());
                commentView.setBookImg (ebook.getPictureUrl ());
                commentView.setTitle (ebook.getTitle ());
                commentView.setCommentTime (comment.getCommentTime ());
                commentView.setCommentStar (comment.getCommentStar ());
                commentView.setComment (comment.getComment ());
                commentViews.add (commentView);
            }
        }
        JSONArray jsonArray = JSONArray.fromObject (commentViews);
        // System.out.println (jsonArray);
        //System.out.println (connectionBooks);
        return jsonArray;
    }

    @GetMapping("/newChat")
    @ResponseBody
    public Result newChat(Integer peopleId,String now,String chat){
        List<Admin> admins = adminService.findAll();
        int index = (int) (Math.random()*admins.size());
        Admin admin = admins.get(index);
        Integer getPeopleId = admin.getPeopleId();
        Chat chat1 = new Chat(null,peopleId,getPeopleId,now,chat,false);
        adminService.addChat(chat1);
        return new Result("200","发送成功");
    }

    @GetMapping("/historyChat")
    @ResponseBody
    public JSONArray historyChat(Integer adminPeopleId,Integer userPeopleId){
        List<Chat> chats = adminService.findHistoryChat(adminPeopleId,userPeopleId);
        JSONArray historyChat = JSONArray.fromObject(chats);
        return historyChat;
    }
}
